layui.extend({
    baseConfig: "/js/pages/baseConfig"
})
layui.use(['form', 'layer', 'laydate', 'table', 'laytpl', 'element', 'util', 'baseConfig', 'upload'], function () {

    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        baseConfig = layui.baseConfig,
        laydate = layui.laydate,
        upload = layui.upload,
        table = layui.table;
    var util = layui.util;
    var tableIns = table.render({
        elem: '#list',
        url: '/cloudDisk/list/',
        page: true, //开启分页
        limit : 100,
        limits : [100],
        totalRow : true, //开启合计行
        text: {none: "Aucun résultat"},
        cellMinWidth: 95,
        height: "full-125",
        id: "listTable",
        cols: [[
            {field: 'id', title: "ID", width:50, align:"center"},
            {
                field: 'cloudDiskNoProfix', title: "编号", width: 200, align: "center", templet: function (d) {
                    var str = "" + d.cloudDiskNoNumber
                    var pad = "0000"
                    var ans = pad.substring(0, pad.length - str.length) + str
                    return d.cloudDiskNoProfix + ans;
                }
            },
            {field: 'cooperativeName', title: "公司名称", width: 200, align: "center"},
            {
                field: 'contentType', title: "文件内容类型", align: 'center', templet: function (d) {
                    switch (d.contentType) {
                        case 1:
                            return "新上传";
                        case 2:
                            return "其他";
                        case 3:
                            return "发票";
                    }
                }
            },
            {
                field: 'adminUserName', title: "状态", align: "center", templet: function (d) {
                    if (d.otherId) {
                        if (d.consumerReviewStatus && d.consumerReviewStatus == "PASS") {
                            return "<span style='color: green'>审核完毕</span>";
                        } else {
                            return "<span style='color: green'>已绑定到消费记录</span>";
                        }
                    } else {
                        return "<span style='color: gray'>未绑定到消费记录</span>";
                    }
                }
            },
            {field: 'invoiceNum', title: "发票号码", align: "center"},
            {field: 'mount', title: "TTC", align: "center"},
            {field: 'manullyDate', title: "日期", align: "center"},
            {field: 'jobNumber', title: "归属人", align: "center"},
            {
                field: 'createTime', title: '上传时间', align: 'center', templet: function (d) {
                    return baseConfig.formatDate(d.createTime);
                }
            },
            {
                title: 'État', width: 300, align: "center", templet: function (d) {
                    var str = "<a class=\"layui-btn layui-btn-xs\" lay-event=\"edit\">编辑</a>";
                    if (d.contentType == 3) {
                        if (d.otherId) {
                            if (d.consumerReviewStatus != "PASS") {
                                str += "<a class=\"layui-btn layui-btn-xs layui-btn-primary\" lay-event=\"handUnBindConsumer\">解除绑定</a>";
                            }
                        } else {
                            str += "<a class=\"layui-btn layui-btn-xs layui-btn-primary\" lay-event=\"del\">删除</a>";
                            str += "<a class=\"layui-btn layui-btn-xs layui-btn-primary\" lay-event=\"handBindConsumer\">发票对应</a>";
                        }
                    }
                    return str;
                }
            }
        ]],
        response: {
            statusCode: 200 //规定成功的状态码，默认：0
        },
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.count, //数据条数
                "data": res.data.data //解析数据列表
            };
        }
    });
    //获取浏览器最大高度，以防页面显示不完全
    var maxHeight = $(window).height();
    var maxWidth = $(window).width();

    //添加/修改/详细查看（readonly=true）
    function addOrUpdateOrDetail(data, readonly) {
        var imgFilePath = "";
        var adminUserId = "";
        var cooperativeName = "";
        var customHouse = "";
        if (data) {
            if (data.imgFileUrl) {
                imgFilePath = data.imgFileUrl;
            }
            if (data.adminUserId) {
                adminUserId = data.adminUserId;
            }
            if (data.cooperativeName) {
                cooperativeName = window.btoa(data.cooperativeName);
            }
            if (data.customHouse) {
                customHouse = data.customHouse;
            }
        }

        var index = layui.layer.open({
            title: "添加",
            type: 2,
            area: [(maxWidth - 10) + 'px', (maxHeight < 800 ? maxHeight - 10 : 800) + 'px'],
            shade: 0.4,
            btnAlign: 'r',
            id: "role", //设定一个id，防止重复弹出
            content: "formData.html?imgFilePath=" + imgFilePath
                + "&adminUserId=" + adminUserId
                + "&cooperativeName=" + cooperativeName
                + "&customHouse=" + customHouse
                + "&jobNumber=" + data.jobNumber
                + "&companyId=" + data.companyId
                + "&id=" + data.id,
            success: function () {
                var body = layui.layer.getChildFrame('body', index);
                if (data) {
                    body.find("input[name=id]").val(data.id).attr("readonly", readonly);//标识是修改还是新增
                    body.find("input[name=name]").val(data.name).attr("readonly", readonly);
                    body.find("input[name=nom]").val(data.nom);
                    body.find("input[name=prenom]").val(data.prenom);
                    body.find("input[name=htMount]").val(data.htMount);
                    body.find("input[name=invoiceNum]").val(data.invoiceNum);
                    body.find("input[name=mount]").val(data.mount);
                    body.find("input[name=htTwenty]").val(data.htTwenty);
                    body.find("input[name=htTen]").val(data.htTen);
                    body.find("input[name=htFive]").val(data.htFive);
                    body.find("input[name=htTwo]").val(data.htTwo);
                    body.find("input[name=htZero]").val(data.htZero);
                    body.find("input[name=manullyDate]").val(data.manullyDate);
                    body.find("select[name=contentType]").val(data.contentType).attr("readonly", readonly);
                    body.find("input[name=entireContent]").val(data.entireContent).attr("readonly", readonly);
                    if (readonly) {
                        body.find("#submitDiv").hide();
                    }
                    form.render();
                } else {
                    body.find("#contentType_div").hide();
                }
            }
        });
    }

    //加载日期选择框
    laydate.render({
        elem: '#manullyDateStart',
        format: 'yyyy-MM-dd',
        trigger: 'click',
        lang: 'en',
        max: 0,
        done: function (value, date) {
            $(".search_btn").click();
        }
    });
    laydate.render({
        elem: '#manullyDateEnd',
        format: 'yyyy-MM-dd',
        lang: 'en',
        trigger: 'click',
        max: 0,
        done: function (value, date) {
            $(".search_btn").click();
        }
    });

    $("input[name=mount]").on("input propertychange", function (e) {
        $(".search_btn").click();
    });
    $("input[name=jobNumber]").on("input propertychange", function (e) {
        $(".search_btn").click();
    });
    $("#contentType").onchange = function() {
        $(".search_btn").click();
    };
    form.on('select(contentType)', function(data){
        $(".search_btn").click();
    });
    //搜索
    $(".search_btn").on("click", function () {
        var mount = $("input[name=mount]").val();
        var manullyDateStart = $("input[name=manullyDateStart]").val();
        var manullyDateEnd = $("input[name=manullyDateEnd]").val();
        var jobNumber = $("input[name=jobNumber]").val();
        var contentType = $("select[name=contentType]").val();
        table.reload("listTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                "jobNumber": jobNumber,
                "mount": mount,
                "manullyDateStart": manullyDateStart,
                "manullyDateEnd": manullyDateEnd,
                "contentType": contentType
            }
        })
    });

    $("#export_excel").on("click", function () {
        var index = layer.msg('导出中，请稍候....', {icon: 16, time: false, shade: 0.8});
        //获取到此时的查询条件
        var mount = $("input[name=mount]").val();
        var manullyDateStart = $("input[name=manullyDateStart]").val();
        var manullyDateEnd = $("input[name=manullyDateEnd]").val();
        var jobNumber = $("input[name=jobNumber]").val();
        var contentType = $("select[name=contentType]").val();
        console.log('contentType', contentType)
        $.post("/cloudDisk/exportAsExcel", {
            "jobNumber": jobNumber,
            "mount": mount,
            "contentType": contentType,
            "manullyDateStart": manullyDateStart,
            "manullyDateEnd": manullyDateEnd
        }, function (res) {
            layer.close(index);
            if (res.code == 200) {
                var exportCount = res.data.exportCount;
                var filePath = res.data.filePath;
                top.layer.alert("导出成功");
                layer.confirm("导出成功,共导出[" + exportCount + "]条数据，确认下载Excel文件？", function (confirmIndex) {
                    window.open(filePath);
                    layer.close(confirmIndex);
                });
            } else {
                top.layer.alert("导出失败");
            }
        });
    });

    $("#invoice_export_excel").on("click", function () {
        var index = layer.msg('导出中，请稍候....', {icon: 16, time: false, shade: 0.8});
        //获取到此时的查询条件
        var mount = $("input[name=mount]").val();
        var manullyDateStart = $("input[name=manullyDateStart]").val();
        var manullyDateEnd = $("input[name=manullyDateEnd]").val();
        var jobNumber = $("input[name=jobNumber]").val();
        var contentType = $("select[name=contentType]").val();
        console.log('contentType', contentType)
        $.post("/cloudDisk/invoiceExportAsExcel", {
            "jobNumber": jobNumber,
            "mount": mount,
            "contentType": contentType,
            "manullyDateStart": manullyDateStart,
            "manullyDateEnd": manullyDateEnd
        }, function (res) {
            layer.close(index);
            if (res.code == 200) {
                var exportCount = res.data.exportCount;
                var filePath = res.data.filePath;
                top.layer.alert("导出成功");
                layer.confirm("导出成功,共导出[" + exportCount + "]条数据，确认下载Excel文件？", function (confirmIndex) {
                    window.open(filePath);
                    layer.close(confirmIndex);
                });
            } else {
                top.layer.alert("导出失败");
            }
        });
    });

    //删除
    function del(ids) {
        layer.confirm('确定删除选中的数据项？', {icon: 3, title: '提示信息'}, function (index) {
            $.post("/cloudDisk/del", {
                "ids": ids
            }, function (res) {
                if (res.code == 200) {
                    tableIns.reload();
                    layer.close(index);
                    top.layer.msg(res.msg);
                } else {
                    top.layer.close(index);
                    top.layer.msg(res.msg);
                }
            });
        });
    }

    //添加按钮，现在需要修改为先上传文件，文件上传成功列再打开预览页面
    upload.render({
        elem: '.add_btn',
        url: '/file/uploadCloudFile?type=uploadCloudFile',
        method: "post",
        accept: "file",
        exts: "pdf",
        before: function () {
            layer.load();
        },
        done: function (res) {
            if (res.code == 200) {
                layer.closeAll();
                var imgFilePath = res.data.imgFilePaths;
                var pdfFilePath = res.data.pdfFilePath;
                var index = layui.layer.open({
                    title: "添加",
                    type: 2,
                    area: [(maxWidth < 1350 ? maxWidth - 10 : 1350) + 'px', (maxHeight < 800 ? maxHeight - 10 : 800) + 'px'],
                    shade: 0.4,
                    btnAlign: 'r',
                    id: "role", //设定一个id，防止重复弹出
                    content: "formData.html?imgFilePath=" + imgFilePath,
                    success: function () {
                        var body = layui.layer.getChildFrame('body', index);
                        body.find("input[name=originFileUrl]").val(pdfFilePath);//标识是修改还是新增
                        body.find("input[name=imgFileUrl]").val(imgFilePath);
                        var analyseContent = res.data.analyseContent;
                        if (analyseContent && analyseContent.entireContent) {
                            body.find("input[name=entireContent]").val(analyseContent.entireContent);
                        }
                        form.render();
                        // setTimeout(function () {
                        //     layui.layer.tips('点击此处返回数据列表', '.layui-layer-setwin .layui-layer-close', {
                        //         tips: 3
                        //     });
                        // }, 500);
                    }
                });
            }
        }
    });

    //批量自动分类
    $(".autoSetType_batch").click(function () {
        layer.load();
        $.post("/cloudDisk/autoSetType", {
            id: -1
        }, function (res) {
            layer.closeAll();
            tableIns.reload();
            top.layer.msg(res.msg);
        });
    });
    //批量自动对应
    $(".bindComsumer_batch").click(function () {
        layer.load();
        $.post("/cloudDisk/bindComsumer", {
            id: -1
        }, function (res) {
            layer.closeAll();
            tableIns.reload();
            top.layer.msg(res.msg);
        });
    });
    //下载发票
    $("#download_invoice").on("click", function () {
        var index = layer.msg('导出中，请稍候....', {icon: 16, time: false, shade: 0.8});
        //获取到此时的查询条件
        $.post("/cloudDisk/exportInvoice", getSearchParam(), function (res) {
            layer.close(index);
            if (res.code == 200) {
                var exportCount = res.data.exportCount;
                var filePath = res.data.filePath;
                top.layer.alert("导出成功");
                layer.confirm("导出成功,共导出[" + exportCount + "]条数据，确认下载文件？", function (confirmIndex) {
                    window.open(filePath);
                    layer.close(confirmIndex);
                });
            } else {
                top.layer.alert("导出失败");
            }
        });
    });

    //获取search表单数据
    function getSearchParam() {
        var mount = $("input[name=mount]").val();
        var manullyDateStart = $("input[name=manullyDateStart]").val();
        var manullyDateEnd = $("input[name=manullyDateEnd]").val();
        var jobNumber = $("input[name=jobNumber]").val();
        var contentType = $("select[name=contentType]").val();
        return {
            "jobNumber": jobNumber,
            "mount": mount,
            "manullyDateStart": manullyDateStart,
            "manullyDateEnd": manullyDateEnd,
            "contentType": contentType
        }
    }

    function autoSetType(id) {
        $.post("/cloudDisk/autoSetType", {
            id: id
        }, function (res) {
            tableIns.reload();
            top.layer.msg(res.msg);
        });
    }

    function bindComsumer(id) {
        $.post("/cloudDisk/bindComsumer", {
            id: id
        }, function (res) {
            tableIns.reload();
            top.layer.msg(res.msg);
        });
    }

    function openHandBindConsumer(data) {
        (maxWidth < 1350 ? maxWidth - 10 : 1350)
        var index = layui.layer.open({
            title: "手动绑定消费流水",
            type: 2,
            area: [(maxWidth < 1350 ? maxWidth - 10 : 1350) + 'px', (maxHeight < 650 ? maxHeight - 10 : 650) + 'px'],
            shade: 0.4,
            btnAlign: 'r',
            id: "handBindConsumer", //设定一个id，防止重复弹出
            content: "hand_bind_consumer.html?cooperativeName=" + data.cooperativeName + "&jobNumber=" + data.jobNumber + "&id=" + data.id,
            success: function () {
            }
        });
    }

    function openHandUnBindConsumer(id) {
        layer.confirm('确定解除绑定选中的数据项？', {icon: 3, title: '提示信息'}, function (index) {
            $.post("/cloudDisk/unBindConsumer", {
                "id": id
            }, function (res) {
                if (res.code == 200) {
                    tableIns.reload();
                    layer.close(index);
                    top.layer.msg(res.msg);
                } else {
                    top.layer.close(index);
                    top.layer.msg(res.msg);
                }
            });
        });
    }

    //列表操作
    table.on('tool(list)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;
        if (layEvent === 'edit') { //编辑
            addOrUpdateOrDetail(data, false);
        } else if (layEvent === 'del') { //删除
            del(data.id);
        } else if (layEvent === 'look') { //预览
            addOrUpdateOrDetail(data, true);
        } else if (layEvent === 'autoSetType') {
            autoSetType(data.id);
        } else if (layEvent === 'bindComsumer') {
            bindComsumer(data.id);
        } else if (layEvent == "handBindConsumer") {
            openHandBindConsumer(data);
        } else if (layEvent == "handUnBindConsumer") {
            openHandUnBindConsumer(data.id);
        }
    });
});
